<template>
  <div class="app-container templateWrapp">
    <FileUpload @getFilesContent="getFilesContent"></FileUpload>
    <el-row :gutter="20">
      <el-col :span="16">
        <div class="grid-content left-add-content">
          <div v-for="(i, index) in content" :key="index" class="editorItemBox">
            <div class="notice" :class="i.selectedMaterialId ? 'materialNotice' : 'editNotice'">
              <div>{{ i.selectedMaterialId ? `素材${i.threeLevelMaterialName || ''}` : '编辑' }}</div>
              <div class="noticebtn">
                <el-button type="warning" plain icon="el-icon-edit" size="mini" @click="saveItemInfo(index)"
                  v-if="i.showEdit" round title="保存"></el-button>
                <el-button type="danger" plain icon="el-icon-delete" @click.stop="clearItem(i, index)" size="mini" round
                  title="删除"></el-button>
                <el-button class="addMaterial" type="primary" plain size="mini"
                  @click="openAddDialog(index)" round title="新增素材">新增素材</el-button>
                <el-button class="addEdit" type="primary" plain size="mini"
                  @click="addItemInIndex(index)" round title="新增编辑">新增编辑</el-button>
              </div>
            </div>
            <div class="ediortAndAddBox">
              <div class="leftContent" @click.stop="editItem(i, index)" :class="{ activeItem: index === formIndex }">
                <div class="editShow" v-if="i.showEdit">
                  <!-- <Editors v-model="content[index].content" width="100%" :min-height="192" @input="editorInput" /> -->
                  <Editors v-model="content[index].content" @getContent="editorInput($event,index)" />
                </div>
                <div class="tempDiv" v-html="i.content" v-else @click="editItemShow(index)"></div>
              </div>
            </div>
            <div class="notice" :class="i.selectedMaterialId ? 'materialNotice' : 'editNotice'">
              <div class="noticebtn">
                <el-button type="warning" plain icon="el-icon-edit" size="mini" @click="saveItemInfo(index)"
                  v-if="i.showEdit" round title="保存"></el-button>
                <el-button type="danger" plain icon="el-icon-delete" @click.stop="clearItem(i, index)" size="mini" round
                  title="删除"></el-button>
                <el-button class="addMaterial" type="primary" plain size="mini"
                  @click="openAddDialog(index)" round title="新增素材">新增素材</el-button>
                <el-button class="addEdit" type="primary" plain size="mini"
                  @click="addItemInIndex(index)" round title="新增编辑">新增编辑</el-button>
              </div>
            </div>
          </div>
          <el-button type="primary" plain size="small" @click="addItem" style="margin-top: 10px;">新增编辑</el-button>
        </div>
        <div class="savaInfo">
          <el-button type="primary" @click="saveMaterial" v-hasPermi="['system:template:update']">保存</el-button>
          <el-button type="primary" @click="saveTemplate" v-hasPermi="['system:template:update']">保存并导出为word</el-button>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content">
          <div class="top">
            <div class="left"><img src="@/assets/images/icon/leftIcon.png" alt="" srcset=""
                style="width: 15px;height: 14px;">子素材库</div>
          </div>
          <div class="list">
            <div class="item" v-for="(i, index) in dTotal" :key="index">
              <div class="title">{{ i.name }}</div>
              <div class="content" v-for="(sub, index1) in i.children" :key="index1">
                <div class="row">
                  <div class="left">{{ sub.name }}</div>
                  <div class="right">
                    <el-popover placement="bottom" width="250" trigger="focus">
                      <div class="searchList" v-if="searchInfoList.length > 0">
                        <p class="showItem" v-for="selectInfo in searchInfoList" @click="handleSelect(selectInfo)">
                          {{ selectInfo.name }}
                        </p>
                        <el-pagination small layout="prev, pager, next" v-show="total > 0" :total="total"
                          :page.sync="queryParams.params.pageNum" :limit.sync="queryParams.params.pageSize"
                          @pagination="getMaterial" :pager-count="5">
                        </el-pagination>
                      </div>
                      <div v-else class="showLoadingTitle">
                        {{ showLoadingTitle ? '搜索中，请稍等' : '暂无数据' }}
                      </div>
                      <el-input placeholder="请输入内容" slot="reference" v-model="i.children[index1].remark"
                        @focus="changeItem(sub, i.children[index1].remark)"
                        @input="changeItem(sub, i.children[index1].remark)"></el-input>
                    </el-popover>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 新增素材对话框 -->
    <el-dialog title="提示" :visible.sync="addIsOpen" width="30%">
      <div class="grid-content" v-if="addIsOpen">
        <div class="top">
          <div class="left"><img src="@/assets/images/icon/leftIcon.png" alt="" srcset=""
              style="width: 15px;height: 14px;">子素材库</div>
        </div>
        <div class="list">
          <div class="item" v-for="(i, index) in dTotal" :key="index">
            <div class="title">{{ i.name }}</div>
            <div class="content" v-for="(sub, index1) in i.children" :key="index1">
              <div class="row">
                <div class="left">{{ sub.name }}</div>
                <div class="right">
                  <el-popover placement="bottom" width="250" trigger="focus">
                    <div class="searchList" v-if="searchInfoList.length > 0">
                      <p class="showItem" v-for="selectInfo in searchInfoList" @click="addHandleSelect(selectInfo)">
                        {{ selectInfo.name }}
                      </p>
                      <el-pagination small layout="prev, pager, next" v-show="total > 0" :total="total"
                        :page.sync="queryParams.params.pageNum" :limit.sync="queryParams.params.pageSize"
                        @pagination="getMaterial" :pager-count="5">
                      </el-pagination>
                    </div>
                    <div v-else class="showLoadingTitle">
                      {{ showLoadingTitle ? '搜索中，请稍等' : '暂无数据' }}
                    </div>
                    <el-input placeholder="请输入内容" slot="reference" v-model="i.children[index1].remark"
                      @focus="changeItem(sub, i.children[index1].remark)"
                      @input="changeItem(sub, i.children[index1].remark)"></el-input>
                  </el-popover>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addIsOpen = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getTemplates, saveMaterial, saveWord, materialSearch } from "@/api/template/template";
// import Editors from '@/components/Wangeditor/editor.vue'
import Editors from '@/components/ckeditor/index.vue';
import { Message } from 'element-ui'
import debounce from '@/utils/debounce'
const debounceGetSearch = debounce(materialSearch, 500)
export default {
  components: {
    Editors,
  },
  name: "Online",
  data() {
    return {
      //新增素材的位置
      addIndex: 0,
      //新增素材弹框是否打开
      addIsOpen: false,
      //编辑框回显数据
      editorHtml: '',
      //编辑框传递给父组件的内容,父组件调接口传递给后端
      editorContent: '',
      showLoadingTitle: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        "name": "",
        "params": {
          "pageSize": 10,
          "pageNum": 1
        },
        "parentId": ""
      },
      searchInfoList: [],
      visible: true,
      templateName: '',
      materialId: '',
      dTotal: [],//素材库列表
      // 表单参数
      form: {},
      // 弹出层标题
      title: "详情",
      open: false,
      formIndex: '',
      firstItem: {
        selectedMaterialId: 0,
        content: ''
      },
      content: [{
        content: "",//富文本的内容
        selectedMaterialId: '',//选中的素材id
        threeLevelMaterialName: ''//选中素材的名字
      }],
      state1: '',
      resorceArr: [],
      restaurants: [
      ],
      templateId: '',//查询的模板id
      ids: [],//保存修改的内容
      focusMaterialId: '',//焦点的id
      // content: [

      // ],
    };
  },
  created() {
    // this.getList()
    let id = this.$route.query.templateId
    this.templateName = this.$route.query.templateName
    this.templateId = id;
    this.getDetails();
    //设置富文本的默认值
    this.showEditorHtml();
  },
  methods: {
    /**上传文件结束 */
    getFilesContent(e) {
      console.log(e);
      this.content.push({
        content: e,//富文本的内容
        selectedMaterialId: '',
        threeLevelMaterialName: ''
      })
    },
    /**在指定位置添加编辑框 */
    addItemInIndex(index) {
      this.addIndex = index + 1;
      const addContent = {
        content: '',//富文本的内容
        selectedMaterialId: ''
      };
      this.content.splice(this.addIndex, 0, addContent)
    },
    //获取编辑框的值
    editorInput(value,index) {
      console.log('value', value,index);
      this.content[index].content = value;

    },
    //弹窗字素材下拉框选中添加
    addHandleSelect(item) {
      // console.log(this.content, '1')
      // console.log('item', item);
      let isSelect = this.ids.includes(item.materialId)
      console.log('isSelect', isSelect);
      if (!isSelect) {//没有选中 的时候就添加进去
        this.ids.push(item.materialId)
        const addData = {
          content: item.content,
          selectedMaterialId: item.materialId,
          threeLevelMaterialName: item.name
        };
        this.content.splice(this.addIndex, 0, addData);
        // if (this.formIndex === '') {//此时不是选中状态
        //   const addData = {
        //     content: item.content,
        //     selectedMaterialId: item.materialId,
        //     threeLevelMaterialName: item.name
        //   }
        //   this.content.splice(this.addIndex, 0, addData)
        // } else {//如果是选中状态就在对应的索引下面插入数据
        //   let newData = this.insert(this.content, {
        //     content: item.content,
        //     selectedMaterialId: item.materialId,
        //     threeLevelMaterialName: item.name
        //   }, this.formIndex + 1);
        //   // console.log(newData, '1')
        // }
      } else {
        Message({ message: '您已添加该素材', type: 'error' })
      }
      for (let k in this.dTotal) {
        for (let m in this.dTotal[k].children) {
          if (this.dTotal[k].children[m].materialId == this.focusMaterialId) {//选中的时候复制给需要的id
            this.dTotal[k].children[m].selectedMaterialId = item.materialId
            this.dTotal[k].children[m].threeLevelMaterialName = item.name
            this.dTotal[k].children[m].remark = null//单纯的将弹框关闭
          }
        }
      }
      console.log(this.dTotal, 'this.dTotal');
      this.addIsOpen = false;
    },
    /**打开新增素材对话框 */
    openAddDialog(index) {
      console.log(index);
      this.addIsOpen = true;
      this.addIndex = index + 1;
      console.log('新增下表', this.addIndex);
    },
    //文本内容回显
    showEditorHtml() {
      //调接口获取富文本的内容
      //获得结果赋给editorHtml
      this.editorHtml = '<p>123456</p>';
    },
    //获取富文本更新后的内容
    catchData(html) {
      // 通过$emit子组件传递过来的文章内容在用户点击“保存”按钮时，将editorContent内容传给后端，后端做保存
      this.editorContent = html;
      console.log('父组件', this.editorContent);
    },
    saveItemInfo(index) {
      this.content.forEach((item, index) => {
        item.showEdit = false
      })
      this.formIndex = '';//此时清除所选的下标
    },
    editItemShow(i) {
      this.content.forEach((item, index) => {
        // 当没有selectedMaterialId的时候方可编辑
        item.showEdit = index == i && !item.selectedMaterialId
      })
    },
    async getMaterial() {
      // let res = await materialSearch(this.queryParams)
      // this.searchInfoList = res.rows
      // this.total = res.total
      debounceGetSearch(this.queryParams).then(res => {
        this.searchInfoList = res.rows
        this.total = res.total
        this.showLoadingTitle = false
        console.log(this.total, 'this.total')
      })
      // console.log(res, 888)
    },
    changeItem(sub, name) {
      this.showLoadingTitle = true
      this.searchInfoList = []
      this.queryParams.name = name;
      this.queryParams.parentId = sub.materialId;
      this.focusMaterialId = sub.materialId//焦点的id
      this.getMaterial()
    },
    async saveTemplate() {
      this.saveMaterial()
      let str = ''
      this.content.map((item) => {
        str += item.content
      })
      let res = await saveWord({ template: str })
      let blob = new Blob([res.data], {
        type: `application/msword` //word文档为msword,pdf文档为pdf
      });
      let objectUrl = URL.createObjectURL(blob);
      let link = document.createElement("a");
      // let fname = this.templateName; //下载文件的名字
      let fname = decodeURI(res.headers["content-disposition"].split("filename=")[1]); //下载文件的名字
      link.href = objectUrl;
      link.setAttribute("download", fname);
      document.body.appendChild(link);
      link.click();
      console.log(blob, 'res')
      // Message({ message: '导出成功', type: 'success' })
    },
    saveMaterial() {
      setTimeout(() => {
        let info = this.content.map(item => {
          return {
            content: item.content,
            threeLevelMaterialId: item.selectedMaterialId,
            threeLevelMaterialName: item.threeLevelMaterialName
          }
        })
        let data = {
          list: info,
          templateId: this.templateId,
        }
        console.log(data, '保存');
        saveMaterial(data).then(res=>{
          Message({ message: '保存成功', type: 'success' })
        })
      }, 0);
    },
    addItem() {
      this.formIndex = '';
      this.content.push(
        {
          selectedMaterialId: '',
          content: '',
          threeLevelMaterialName: '',
          editContent: '',
          showEdit: false,
        }
      )
    },
    editItem(row, index) {
      if (this.formIndex === '') { //重复点的实时就取消默认选择
        this.formIndex = index;
      } else {
        this.formIndex = ''
      }
      //根据是否有selectedMaterialId判断是否从素材中获取的
      if (row.selectedMaterialId) return Message({ message: '这是素材内容，不能编辑', type: 'error' })
      this.form = Object.assign({}, row);
    },
    clearItem(e, index) {
      this.content.splice(index, 1)
      for (let i = 0; i < this.ids.length; i++) { //删除id
        //先判断是否为空字符串
        if (e.selectedMaterialId) {
          //不是空字符串，判断ids是否存在，存在则删除
          console.log(this.ids.includes(e.selectedMaterialId))
          if (this.ids.includes(e.selectedMaterialId)) {
            // 判断 id 为 4 的对象是否存在，
            this.ids.splice(i, 1) // 存在即删除
          }
        }

      }
      // for (let i = 0; i < this.content.length; i++) { //删除内容
      //   console.log(this.content[i].selectedMaterialId.indexOf(e.selectedMaterialId))
      //   if (this.content[i].selectedMaterialId.indexOf(e.selectedMaterialId) > -1) {
      //     // 判断 id 为 4 的对象是否存在，
      //     this.content.splice(i, 1) // 存在即删除
      //   }
      // }
    },
    async getDetails() {
      //每次都清空
      this.content = []
      this.ids = []
      let response = await getTemplates({ templateId: this.templateId })
      this.dTotal = response.data.materialTree;
      this.content = response.data.materialToTemplateDto.list.map(item => {
        return {
          selectedMaterialId: item.threeLevelMaterialId,
          content: item.content,
          threeLevelMaterialName: item.threeLevelMaterialName
        }
      })
      this.ids = response.data.materialToTemplateDto.list.map(item => {
        return item.threeLevelMaterialId
      })
    },
    insert(arr, item, index) {
      let newArr = arr.slice(0)
      newArr.splice(index, 0, (JSON.parse(JSON.stringify(item))))
      return newArr
    },
    handleSelect(item) {
      let isSelect = this.ids.includes(item.materialId)
      if (!isSelect) {//没有选中 的时候就添加进去
        this.ids.push(item.materialId)

        this.content.push({
          content: item.content,
          selectedMaterialId: item.materialId,
          threeLevelMaterialName: item.name
        })
        // if (this.formIndex === '') {//此时不是选中状态
        //   this.content.push({
        //     content: item.content,
        //     selectedMaterialId: item.materialId,
        //     threeLevelMaterialName: item.name
        //   })
        // } else {//如果是选中状态就在对应的索引下面插入数据
        //   let newData = this.insert(this.content, {
        //     content: item.content,
        //     selectedMaterialId: item.materialId,
        //     threeLevelMaterialName: item.name
        //   }, this.formIndex + 1)
        //   console.log(newData, 'newData')
        //   // this.content.splice(this.formIndex, 0, {
        //   //   content: item.content,
        //   //   selectedMaterialId: item.materialId
        //   // })
        // }
        // console.log(this.content, '2')
      } else {
        Message({ message: '您已添加该素材', type: 'error' })
      }
      for (let k in this.dTotal) {
        for (let m in this.dTotal[k].children) {
          if (this.dTotal[k].children[m].materialId == this.focusMaterialId) {//选中的时候复制给需要的id
            this.dTotal[k].children[m].selectedMaterialId = item.materialId
            this.dTotal[k].children[m].threeLevelMaterialName = item.name
            this.dTotal[k].children[m].remark = null//单纯的将弹框关闭
          }
        }
      }
    },
    filterChildren() {
      for (let k in this.dTotal) {
        for (let m in this.dTotal[k].children) {
          if (this.dTotal[k].children[m].materialId == this.focusMaterialId) {
            this.resorceArr = this.dTotal[k].children[m].children
          }
        }
      }
      // console.log(this.resorceArr, 'this.resorceArr')
    },
    changeInput(e, value) {
      this.focusMaterialId = e.materialId//焦点的id
      this.filterChildren()
    },
    getList() {
      list().then(response => {
        this.dTotal = response.rows;
        console.log(this.dTotal, 'dTotal')
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.content.forEach((i, k) => {
        if (k == this.formIndex) {
          i.content = this.form.content
        }
      })
      this.form = {};
      this.open = false
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    querySearch(queryString, cb) {
      var restaurants = this.resorceArr;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

  }
};
</script>
<style scoped lang="scss">
.ediortAndAddBox {
  display: flex;
}

::v-deep .el-dialog__wrapper {
  // margin-left: -122px !important;
  // top: 0;
  // right: auto !important;
  // bottom: auto !important;
  left: -6% !important;
  // overflow: auto !important;
  // margin: 0 !important;
}

// ::v-deep .searchList:hover>showItem {
//   background: #f8f7f7 !important;
//   cursor: pointer !important;
// }
.activeItem {
  border: 1px solid #F9B37D !important;
}

.searchList p:hover {
  background: #f8f7f7 !important;
  cursor: pointer !important;
}

.savaInfo {
  margin-top: 20px;
}

.showLoadingTitle {
  color: #333;
  text-align: center;
  font-size: 14px;
}

.left-add-content {
  border-radius: 6px;
  border: 1px solid #F0F1F5;
  padding: 10px;
  min-height: 500px;
  padding-bottom: 50px;
}

.leftContent {
  min-height: 150px;
  width: 100%;
  cursor: pointer;
  position: relative;
  border: 1px solid #ccc;
  display: flex;

  .close {
    position: absolute;
    top: 10px;
    cursor: pointer;
    right: 10px;
  }

  .tempDiv {
    padding-left: 10px;
    flex: 1;

    table {
      border: 1px solid #ccc !important;
    }
  }

  .editShow {
    flex: 1;
    width: 100%;
    // min-height: 250px;
  }
}

.empty-content {
  height: 100%;
  width: 100%;
  cursor: pointer;
}

.list {
  display: flex;
  flex-direction: column;

  .item {
    margin-top: 10px;

    .title {
      color: #F9B37D;
      font-family: PingFang SC;
      font-size: 14px;
      font-style: normal;
      font-weight: 500;
      line-height: normal;
      text-align: left;
    }

    .content {
      margin-top: 15px;
      color: #333;
      font-family: PingFang SC;
      font-size: 14px;

      .row {
        margin-top: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .left {
          width: 35%;
        }

        .right {
          width: 65%;
          display: flex;
          align-items: center;

          .searchList {
            p {
              &:hover {
                background: #f8f7f7;
                cursor: pointer;
              }
            }
          }

          .close {
            font-size: 22px;
            margin-left: 10px;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.top {
  display: flex;
  justify-content: space-between;
  color: #333;
  margin: 0 0 15px 0;

  .left {
    img {
      margin-right: 10px;
    }
  }

  .right {}


}

.notice {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.materialNotice {
  background-color: #ffeded;
}

.editNotice {
  background-color: #e8f4ff;
}

.noticebtn {
  position: absolute;
  right: 10px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.editorItemBox {
  overflow-x: auto;
  margin-bottom: 10px;
}

::v-deep td,
::v-deep th {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}</style>
